package com.example.myapplication;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;

import com.example.myapplication.adapter.NewsSortAdapter;
import com.example.myapplication.databinding.ActivitySettingSortBinding;
import com.example.myapplication.util.ItemTouchHelperCallback;
import com.example.myapplication.util.Network;
import com.example.myapplication.util.TagUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SettingSortActivity extends AppCompatActivity {
    private final String TAG = "SettingSortActivity";
    private ActivitySettingSortBinding viewBinding;
    //已经添加的标签
    private List<String> newsSortAdd = new ArrayList<>();
    //未添加的标签
    private List<String> newsSortNoAdd = new ArrayList<>();
    //所有标签
    private Map<String, String> map = new HashMap<>(Network.getNewsSortList());

    SharedPreferences sp;

    //添加标签
    NewsSortAdapter newsSortAdapter;
    //未添加标签
    NewsSortAdapter newsSort2Adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewBinding = ActivitySettingSortBinding.inflate(getLayoutInflater());
        setContentView(viewBinding.getRoot());
        //初始化SP
        sp  = getSharedPreferences(TagUtil.NEWS_SORT_PREFS, MODE_PRIVATE);
        /* 显示App icon左侧的back键 */
        setBar();
        //设置数据
        initData();
    }


    private void initData() {
        getSpData();
        //点击完成发送广播
        viewBinding.tvSettingFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //存储数据
                saveData();
                //发送广播
                setBroadcastManager();
                //关闭当前页面，返回上一页
                finish();
            }
        });

        //设置已添加标签
        addTab();
        //设置未添加标签
        noAddTab();
    }

    private void setBar() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar!=null){
            actionBar.setTitle(R.string.news_sort);
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

    }

    //获取SP中的数据
    private void getSpData() {
        //sp中有数据
        if (sp.contains(TagUtil.NEWS_SORT_PREFS_LIST)) {
            String listJson1 = sp.getString(TagUtil.NEWS_SORT_PREFS_LIST, "");
            if (!listJson1.equals("")) {
                Gson gson = new Gson();
                newsSortAdd = gson.fromJson(listJson1, new TypeToken<List<String>>() {
                }.getType());
            }
            for(Map.Entry<String,String> entry:map.entrySet()){
                if (!newsSortAdd.contains(entry.getKey())){
                    newsSortNoAdd.add(entry.getKey());
                }
            }
        }else{
            for(Map.Entry<String,String> entry:map.entrySet()){
                newsSortAdd.add(entry.getKey());
            }
        }
    }

    /**
     * 设置添加按钮
     */
    private void noAddTab() {
        viewBinding.rvSettingList2.setLayoutManager(new GridLayoutManager(SettingSortActivity.this,3));
        newsSort2Adapter = new NewsSortAdapter(SettingSortActivity.this, newsSortNoAdd);
        viewBinding.rvSettingList2.setAdapter(newsSort2Adapter);
        newsSort2Adapter.setOnItemClickListener(new NewsSortAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Log.d(TAG, "onItemClick: "+ newsSortNoAdd.get(position) + "被添加");
                newsSortAdd.add(newsSortNoAdd.get(position));
                newsSortAdapter.setData(newsSortAdd);
                newsSortNoAdd.remove(position);
                newsSort2Adapter.setData(newsSortNoAdd);

            }
        });
    }

    //设置tab
    private void addTab() {
        viewBinding.rvSettingList1.setLayoutManager(new GridLayoutManager(SettingSortActivity.this,3));
        newsSortAdapter = new NewsSortAdapter(SettingSortActivity.this, newsSortAdd);
        viewBinding.rvSettingList1.setAdapter(newsSortAdapter);
        newsSortAdapter.setOnItemClickListener(new NewsSortAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Log.d(TAG, "onItemClick: "+ newsSortAdd.get(position) + "被删除");
                newsSortAdapter.setData(newsSortAdd);
                newsSortNoAdd.add(newsSortAdd.get(position));
                newsSort2Adapter.setData(newsSortNoAdd);
                newsSortAdd.remove(position);
                newsSortAdapter.setData(newsSortAdd);

            }
        });

        ItemTouchHelperCallback helperCallback = new ItemTouchHelperCallback(newsSortAdapter);
        ItemTouchHelper helper = new ItemTouchHelper(helperCallback);
        helper.attachToRecyclerView(viewBinding.rvSettingList1);
    }

    private void saveData() {
        Gson gson = new Gson();
        String str = gson.toJson(newsSortAdd);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(TagUtil.NEWS_SORT_PREFS_LIST,str);
        edit.commit();
    }

    private void setBroadcastManager() {
        Log.d(TAG, "onClick: 发送服务");
        //发送广播
        Intent intent=new Intent();
        //指定广播的名字
        intent.setAction(TagUtil.BROADCAST_NAME);
        Bundle bundle = new Bundle();
        //list实现了Serializable
        bundle.putSerializable(TagUtil.BROADCAST_SERIALIZABLE_DATA,(Serializable) newsSortAdd);
        intent.putExtras(bundle);
        //本地广播：推荐应用内通信
        LocalBroadcastManager.getInstance(SettingSortActivity.this).sendBroadcast(intent);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); //关闭当前页面
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}